import { BaseService, CoolCommException } from "@cool-midway/core";
import { Inject, Provide } from "@midwayjs/core";
import { Equal, Repository } from "typeorm";
import { ProviderTeamEntity } from "../entity/team";
import { InjectEntityModel } from "@midwayjs/typeorm";
import { Context } from "@midwayjs/koa";
import { Utils } from "../../../comm/utils";

@Provide()
export class ProviderTeamService extends BaseService {

    @InjectEntityModel(ProviderTeamEntity)
    providerTeamEntity: Repository<ProviderTeamEntity>

    @Inject()
    ctx: Context


    @Inject()
    utils: Utils

    /**
     * 生成团队邀请码
     * @returns
     */
    async getCurrentTeamInviteCode(): Promise<string> {
        const team = await this.providerTeamEntity.findOne({
            where: {
                ownerProviderId: this.ctx.provider.id
            }
        })
        if (!team) {
            throw new CoolCommException('您还未创建团队')
        }
        return team.inviteCode
    }


    /**
     * 根据团队ID查询团队
     * @param teamId 
     * @returns 
     */
    async getTeamById(teamId: number) {
        return this.providerTeamEntity.findOne({
            where: { id: Equal(teamId) }
        })
    }

    /**
     * 根据服务人员ID查询团队是否存在
     * @param providerId 服务人员ID
     * @returns 是否存在
     */
    async existsTeamByProviderId(providerId: number) {
        return this.providerTeamEntity.exists({
            where: { ownerProviderId: Equal(providerId) }
        });
    }

    /**
     * 根据服务人员ID查询团队
     * @param providerId 服务人员ID
     * @returns 团队
     */
    async getTeamByProviderId(providerId: number) {
        return this.providerTeamEntity.findOne({
            where: { ownerProviderId: Equal(providerId) }
        })
    }

    /**
     * 根据团队邀请码查询团队
     * @param inviteCode 团队邀请码
     * @returns 团队
     */
    async getByInviteCode(inviteCode: string) {
        if (!inviteCode) {
            throw new CoolCommException('团队邀请码不能为空')
        }
        return await this.providerTeamEntity.findOne({
            where: { inviteCode: Equal(inviteCode) }
        })
    }


    // 发起加入团队请求
    async joinRequest(inviteCode: string) {
        const team = await this.getByInviteCode(inviteCode)
        if (!team) {
            throw new CoolCommException('团队邀请码不存在')
        }
        
    }

    async modifyBefore(data: ProviderTeamEntity, type: "delete" | "update" | "add") {
        if (type === "add") {
            data.inviteCode = await this.utils.generateUniqueCode();
        }
    }
}